package util.webSearch;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.Hashtable;

import util.io.FileInput;
import util.io.URLInput;
import util.parser.JsonParser;

public class DeliciousQuery {

	
	public static void main(String args[]) throws IOException, URISyntaxException{
		
		
		String url="http://en.wikipedia.org/wiki/Odysseus";
		
		
		
		String path ="/home/sergio/Documents/hospital/health_websites/list_nl.txt";
		FileInput in = new FileInput(path);
		
		String line = in.readString();
		while(line!=null){
			
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			line = in.readString();
			if(line==null) continue;
			url=line.trim();
			
			DeliciousURLInfo info  =DeliciousQuery.parseDeliciousInfoFromURL(url, null); 
			if(info==null) continue;
			 Hashtable<String, Long> tags = info.getFrequent_tags();
			 
			 Enumeration<String> keys = tags.keys();
			 
			 while(keys.hasMoreElements()){
				 
				 String tag= keys.nextElement();
				 
				 System.out.println(url+"\t"+tag+"\t"+tags.get(tag));
			 
			 }
			 
									
		}
		
		
		 
	}
	
	public static  DeliciousURLInfo parseDeliciousInfoFromURL(String url, String path_domains) throws IOException, URISyntaxException {
		// hash url to MD5

		if (!url.startsWith("http")) {

			url = "http://" + url;

		}

		String md5 = null;
		url=url.trim();
		try {
			md5 = hashStringMD5(url);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String del_url = "http://feeds.delicious.com/v2/json/urlinfo/" + md5;
		del_url= del_url.trim();
		String post = URLInput.submitURLRequestUDF(del_url, path_domains);
		DeliciousURLInfo del = JsonParser.parseDeliciousInfoPost(post);
		
		return del;

	}

	public static String hashStringMD5(String string)
			throws NoSuchAlgorithmException {

		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(string.getBytes());

		byte byteData[] = md.digest();

		// convert the byte to hex format method 1
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16)
					.substring(1));
		}

		// convert the byte to hex format method 2
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			String hex = Integer.toHexString(0xff & byteData[i]);
			if (hex.length() == 1)
				hexString.append('0');
			hexString.append(hex);
		}

		return hexString.toString();

	}

}
